<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\common;

use app\model\agent\AgentLevel;
use app\model\agent\AgentMoneyLog;
use app\model\agent\AgentRelation;
use app\model\order\OrderItems;
use app\model\product\product\StoreProduct;
use app\model\user\User;
use crmeb\exceptions\ApiException;

/**
 * 分佣逻辑处理工具类
 */
class AgentTool
{
    /**
     * @var array
     * 订单商品
     */
    public $orderItems = [];

    /**
     * @return AgentTool
     * 静态调用入口
     */
    public static function init() : AgentTool
    {
        return new static();
    }

    /**
     * @param $method
     * @param $orderId
     * @param $userId
     * @return mixed
     * 分销逻辑入口
     */
    public function agent($method, $orderId, $userId)
    {
        //获取订单子表
        $this->orderItems = OrderItems::where('order_id', $orderId)->select()->toArray();
        //分销
        $dictionary = [
            'pay' => 'start',//订单支付时开始分销
            'cancel' => 'rollBack',//订单取消时分销回滚
        ];
        $class = $dictionary[$method];

        return $this->$class($userId);
    }

    /**
     * @param $userId
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 开始分销
     */
    public function start($userId)
    {
        //获取用户分销等级
        //$agentLevel = $this->getAgentLevel($userId);
        //获取关联的分销员
        $agentRelation = $this->getAgentRelation($userId);
        if(empty($agentRelation)) return ;
        /**
         * 开始分销
         * 1、写入分销抽成
         * 2、写入分销行为统计
         */
        $agentLevel = $this->getAgentLevel($userId);
        $keyArray = [
            '1' => 'one_brokerage',
            '2' => 'two_brokerage',
            '3' => 'three_brokerage',
            '4' => 'four_brokerage',
        ];
        //分销抽成
        $now = time();
        foreach($this->orderItems as $key => $val) {
            $commission_money = StoreProduct::find($val['product_id'])->toArray();
            if(isset($agentRelation['first_puid']) && $agentRelation['first_puid'] > 0){
                $commission = $agentLevel[$keyArray[1]];
                $agentMoneyLogsData = [
                    'user_id' => $agentRelation['first_puid'],
                    'order_id' => $val['order_id'],
                    'buyer_uid' => $userId,
                    'product_id' => $val['product_id'],
                    'product_att_value_unique' => $val['product_attr_value_unique'],
                    'money' => bcdiv($commission_money['commission'] * $commission, 100, 2),
                    'money_type' => 1,
                    'add_time' => $now
                ];
                $agentMoneyLogId = AgentMoneyLog::insertGetId($agentMoneyLogsData);
                if(!$agentMoneyLogId) {
                    throw new ApiException(100005);
                }
            }
            if(isset($agentRelation['second_puid']) && $agentRelation['second_puid'] > 0){
                $commission = $agentLevel[$keyArray[2]];
                $agentMoneyLogsData = [
                    'user_id' => $agentRelation['second_puid'],
                    'order_id' => $val['order_id'],
                    'buyer_uid' => $userId,
                    'product_id' => $val['product_id'],
                    'product_att_value_unique' => $val['product_attr_value_unique'],
                    'money' => bcdiv($commission_money['commission'] * $commission, 100, 2),
                    'money_type' => 2,
                    'add_time' => $now
                ];
                $agentMoneyLogId = AgentMoneyLog::insertGetId($agentMoneyLogsData);
                if(!$agentMoneyLogId) {
                    throw new ApiException(100005);
                }
            }
            if(isset($agentRelation['third_puid']) && $agentRelation['third_puid'] > 0){
                $commission = $agentLevel[$keyArray[3]];
                $agentMoneyLogsData = [
                    'user_id' => $agentRelation['third_puid'],
                    'order_id' => $val['order_id'],
                    'buyer_uid' => $userId,
                    'product_id' => $val['product_id'],
                    'product_att_value_unique' => $val['product_attr_value_unique'],
                    'money' => bcdiv($commission_money['commission'] * $commission, 100, 2),
                    'money_type' => 3,
                    'add_time' => $now
                ];
                $agentMoneyLogId = AgentMoneyLog::insertGetId($agentMoneyLogsData);
                if(!$agentMoneyLogId) {
                    throw new ApiException(100005);
                }
            }
            if(isset($agentRelation['four_puid']) && $agentRelation['four_puid'] > 0){
                $commission = $agentLevel[$keyArray[4]];
                $agentMoneyLogsData = [
                    'user_id' => $agentRelation['second_puid'],
                    'order_id' => $val['order_id'],
                    'buyer_uid' => $userId,
                    'product_id' => $val['product_id'],
                    'product_att_value_unique' => $val['product_attr_value_unique'],
                    'money' => bcdiv($commission_money['commission'] * $commission, 100, 2),
                    'money_type' => 4,
                    'add_time' => $now
                ];
                $agentMoneyLogId = AgentMoneyLog::insertGetId($agentMoneyLogsData);
                if(!$agentMoneyLogId) {
                    throw new ApiException(100005);
                }
            }

        }

        //分销行为统计
        $agentBehaviourStatisticsData = [];
        $agentBehaviourStatisticsData[] = [
            'user_id' => '',
            'sale_count' => '',
            'register_nums' => '',
            'invitee_nums' => '',
            'product_share_nums' => '',
            'product_share_join_nums' => '',
            'product_share_view_nums' => '',
        ];

    }

    /**
     * @param $userId
     * @param $commission
     * @return void
     * 分销回滚
     */
    public function rollBack($userId)
    {

    }

    /**
     * @param $userId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取分销等级
     */
    public function getAgentLevel($userId) {
        $result = [];
        $agentLevel = User::where('uid', $userId)->value('agent_level');

        if($agentLevel) {
            $agentLevelRow = AgentLevel::where('id', $agentLevel)->find();
            if(!empty($agentLevelRow)) {
                $result = [
                    'agent_level_id' => $agentLevelRow->id,
                    'one_brokerage' => $agentLevelRow->one_brokerage,
                    'two_brokerage' => $agentLevelRow->two_brokerage,
                    'three_brokerage' => $agentLevelRow->three_brokerage,
                    'four_brokerage' => $agentLevelRow->four_brokerage,
                ];
            }
        }

        return $result;
    }

    /**
     * @param $userId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取关联分销员
     */
    public function getAgentRelation($userId)
    {
        $result = AgentRelation::where('uid', $userId)->find();

        return !empty($result) ? $result->toArray() : [];
    }

    /**
     * @param $userId
     * @param $level
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取分销比例
     */
    public function getCommission($userId, $level)
    {
        $agentLevel = $this->getAgentLevel($userId);
        $keyArray = [
            '1' => 'one_brokerage',
            '2' => 'two_brokerage',
            '3' => 'three_brokerage',
            '4' => 'four_brokerage',
        ];

        return $agentLevel[$keyArray[$level]];
    }
}